package thread;

/**
 * 测试多线程并发安全问题
 */
public class SyncDemo1 {
    public static boolean success1 = false;//表示1号线程是否取款成功
    public static boolean success2 = false;//表示2号线程是否取款成功

    public static void main(String[] args) {
        Bank bank = new Bank();
        int sum = 0;//记录一共尝试了多少次
        while(true) {
            sum++;
            //创建两天线程模拟两个人同时从一个账号取款
            Thread t1 = new Thread() {
                public void run() {
                    success1 = bank.getMoney(20000);
                }
            };
            Thread t2 = new Thread() {
                public void run() {
                    success2 = bank.getMoney(20000);
                }
            };
            t1.start();
            t2.start();
            try {
                //将主线程阻塞一下，等待t1和t2执行完毕，便于下面输出结果
                Thread.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if(success1&&success2){//如果同时取款成功，则说明出现了并发安全问题(可邢可拷)
                System.out.println("取款成功！共尝试:"+sum+"次");
                break;
            }else{
                bank.saveAccount(20000);//没成功则再将20000存回去
                success1 = false;
                success2 = false;
            }
        }
    }
}
